package com.roc.web.action.operator;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.AuditingItem;
import com.roc.pojo.Operators;
import com.roc.pojo.OrgBean;
import com.roc.service.IMerchantServices;
import com.roc.service.IPagenitionService;
import com.roc.service.IRoleService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.constant.AuditingResultCodeType;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Company: </p>
* @author 
* @date 2016年11月21日下午1:44:01
*/
@Component
@Scope("prototype")
@Namespace("/check")
public class OperatorCheckAction extends PaginationBaseAction{

	private Logger logger=LogManager.getLogger(OperatorCheckAction.class);
	private OperatorCheckSearchCondition searchCondition;
    private Operators merchant;
	private String idea;
	private Map<String, String> roleTypes=new TreeMap<String, String>();
	private List<OrgBean> orgList=new ArrayList<OrgBean>();
	@Autowired
	IorgService orgService;	
	@Autowired
	IPagenitionService pagenitionService;
	@Autowired 
	IMerchantServices merchantServices;
	@Autowired
	IPowerInfoService powerInfoService;
	@Autowired
	IRoleService roleService;
	
	private Operators oper;
	private AuditingItem auditing;
	
	private String[] agentList;
	
	

	@Action(value = "init", results = { @Result(name = "success", location = "/pages/operator/operator_check.jsp")
    })
    public String init() throws Exception{
      
		try{
			addActionError("作废了");
			//org();

		}catch (Exception e) {
			// TODO: handle exception
			addActionError("加载信息失败，请联系客服人员");
			logger.error(e.getMessage(),e);
		}
		
       return SUCCESS;
    }
	
	//查询机构
	public void org() throws Exception{
		Operators loginOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		try{
			orgList=orgService.listOrgs(loginOperators);
			
			
			roleTypes=dealRoleType(loginOperators, ConfigProperties.getRoleTypeProperties());
		
		}
		catch (Exception e) {
			// TODO: handle exception
			throw new Exception("加载信息失败，请联系客服人员");
		}
		
			
    }
	
	
	
	/*查询*/
	@Action(value = "queryOperatorCheckYJ", 
			results = { @Result(name = "success", location = "/pages/operator/operator_check.jsp")
    })
	public String search() throws Exception{
		
		Operators logingOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		
		if(searchCondition==null){
			searchCondition=(OperatorCheckSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new OperatorCheckSearchCondition();
			}
		}
		try {
			org();
			
			if(Role.AGENT.getCode().equals(logingOperators.getRoleType())){//代理商
				 List<Operators> opList=merchantServices.listAllSubMerchants(logingOperators.getId());
				 agentList= new String[opList.size()];
				 for (int i=0;i<opList.size();i++) {
					 
					Operators o=opList.get(i);
					agentList[i]=Long.toString(o.getId());
					
				}
			   searchCondition.setAgentId(agentList);
			}
			
			//this.setCurrentPage(this.checkCurrentPage());
			int rows=pagenitionService.count(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAll(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);

			}
			dealWithTheListSpecially(searchRsList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			
		} catch (ServiceException e) {
			
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			
		}
		
		return SUCCESS;
	}
	
	@Action(value = "operatorCheckInfo", 
			results = { @Result(name = "success", location = "/pages/operator/operator_checkinfo.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String operatorCheckInfo() throws Exception{
		
		try{
			org();
			List<Long> operatorIds=this.getMulti_sel();
			if(operatorIds==null||operatorIds.size()==0){
				addActionError("请选择一个操作员");
				return search();
			}
			long id=operatorIds.get(0);
			
			oper=powerInfoService.loadOperatorsById(id);
			for(OrgBean bean:orgList){
				if(oper.getOrgCode().equals(bean.getOrg_code())){
					oper.setOrgName(bean.getOrg_name());
				}
			}
			oper.setRoleName(roleTypes.get(oper.getRoleType()));
			Map<String,String> auditingMap=new LinkedHashMap<String,String>();
			auditingMap.put(AuditingResultCodeType.PASS.getCode(),AuditingResultCodeType.PASS.getName());
			//auditingMap.put(AuditingResultCodeType.REFUSE.getCode(),AuditingResultCodeType.REFUSE.getName());
			auditingMap.put(AuditingResultCodeType.INCOMPLETE_INFO.getCode(),AuditingResultCodeType.INCOMPLETE_INFO.getName());
			
			getRequest().setAttribute("auditingMap",auditingMap);
		}catch(ServiceException e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
		}
		
		return SUCCESS;
		
	}
	
	
	
	@Action(value = "operAuditing", 
			results = { @Result(name = "success",type="chain", location = "queryOperatorCheckYJ"),
			@Result(name = "input",type="chain", location = "/pages/operator/operator_check.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String operAuditing()throws Exception{
		Operators loginOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try{
			if(oper==null){
	        	addActionError("请选择一个操作员");
				return SUCCESS;
	        }
	        
	        powerInfoService.auditingOperator(oper, loginOperators.getAccountNo(), auditing);
	        addActionMessage(loginOperators.getAccountNo()+"对操作员【"+oper.getAccountNo()+"】进行审核");
		}catch(ServiceException e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}
	
	@Override
	protected void dealWithTheListSpecially(List<Object> list) {
		// TODO Auto-generated method stub
		super.dealWithTheListSpecially(list);
		Map<String, String> roleTypes=ConfigProperties.getRoleTypeProperties();
		List<Object> tempList=new ArrayList<Object>();
		for(Object obj:list){
			Operators temp=(Operators)obj;
			for(OrgBean bean:orgList){
				if(temp.getOrgCode().equals(bean.getOrg_code())){
					temp.setOrgName(bean.getOrg_name());
				}
			}
			
			temp.setRoleName(roleTypes.get(temp.getRoleType()));
			tempList.add(temp);
		}
		searchRsList=tempList;
	}
	
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
		
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_BEAN_OPRATOR_CHECK, searchCondition);
		
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (OperatorCheckSearchCondition)getSession().getAttribute(SEARCH_SESSION_BEAN_OPRATOR_CHECK);
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}

	
	
	public OperatorCheckSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(OperatorCheckSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public Operators getMerchant() {
		return merchant;
	}

	public void setMerchant(Operators merchant) {
		this.merchant = merchant;
	}

	public String getIdea() {
		return idea;
	}

	public void setIdea(String idea) {
		this.idea = idea;
	}
	
	public Operators getOper() {
		return oper;
	}

	public void setOper(Operators oper) {
		this.oper = oper;
	}

	public Map<String, String> getRoleTypes() {
		return roleTypes;
	}

	public void setRoleTypes(Map<String, String> roleTypes) {
		this.roleTypes = roleTypes;
	}

	public List<OrgBean> getOrgList() {
		return orgList;
	}

	public void setOrgList(List<OrgBean> orgList) {
		this.orgList = orgList;
	}

	public AuditingItem getAuditing() {
		return auditing;
	}

	public void setAuditing(AuditingItem auditing) {
		this.auditing = auditing;
	}

}
